<template>
<div class="statistics-data-box graph-modal-box">
    <div class="data-overview-box" v-if="options.length > 0">
        <div class="filter-part">
          <el-select v-model="currVal" @change="handleSelect">
            <el-option v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
        <!-- 数据统计-总览 -->
        <div class="data-top-box">
            <el-card class="box-card-top">
                <div class="time-tips">
                  <span>以下为 {{timeTips.pie}} 的数据</span>
                  <quality-box v-if="getControl" :content="`${timeTips.pie} 的数据`" :dateTips="timeTips.pie" text="say医废数据总览汇总"></quality-box>
                </div>
                <ul>
                    <li v-for="(item,index) in overviewData" :key="index">
                        <div v-if="index < 3">
                            <h1 style="font-size: 2em;margin: 0.67em 0;">
                                <span>{{item.number}}</span>
                                <span v-if="index == 0" class="cn">袋</span>
                                <span v-if="item.number.toString().indexOf('kg') == -1 && index == 2">kg</span>
                            </h1>
                            <h3>{{item.title}}</h3>
                        </div>
                        <!-- <div class="unsign-hours" v-else>
                            <h1>
                                <span>{{item.number}}</span>
                            </h1>
                            <h3>{{item.title}}</h3>
                            <h3 class="unsign-check-btn" @click="showModal">点击查看</h3>
                        </div> -->
                    </li>
                </ul>
            </el-card>
            <el-card class="box-card-top">
                <div class="time-tips">
                  <span>以下为 {{timeTips.pie}} 的数据</span>
                </div>
                <div class="top-right" @click="handleShowBigPaintPie">
                    <div class="no-tips" v-if="pieData.length == 0">
                        <h2>暂无数据</h2>
                    </div>
                    <div ref="pie-today" class="pie-charts" v-show="currPieTab == 1 && pieData.length > 0"></div>
                    <div ref="pie-week" class="pie-charts" v-show="currPieTab == 2 && pieData.length > 0"></div>
                    <div ref="pie-month" class="pie-charts" v-show="currPieTab == 3 && pieData.length > 0"></div>
                </div>
                <div class="right-tab pie">
                    <ul>
                        <li v-for="item in pieTab" :key="item.id" :class="[{'tab-active': item.isActive && pieDay.length == 0}]" @click="selectTab(item.id ,'pie')">{{item.title}}</li>
                        <li :class="['date-box',{'tab-active':pieDay.length != 0}]">
                            检索
                            <ekt-date-picker :pickDate="pieDay" @handleChange="handlePieChangeTime"></ekt-date-picker>
                        </li>
                    </ul>
                </div>
                <nav-switch
                    :currSwitch="currPieSwitch"
                    :stats="'pie'"
                    @handleClick="showStats"
                />
            </el-card>
        </div>

        <el-card class="box-card-bottom">
            <div class="time-tips">
              <span>以下为 {{timeTips.bar}} 的数据</span>
              <quality-box v-if="getControl" :content="`${timeTips.bar} 的数据`" :dateTips="timeTips.bar" text="say医废数据总览按日分布"></quality-box>
            </div>
            <div class="data-bottom-box">
                <div ref="bar-total-week" class="total-charts" v-show="currBarTab == 1 && !isOnlyTotal"></div>
                <div ref="bar-total-month" class="total-charts" v-show="currBarTab == 2 && !isOnlyTotal"></div>

                <div ref="bar-total-week-only" class="total-charts" v-show="currBarTab == 1 && isOnlyTotal"></div>
                <div ref="bar-total-month-only" class="total-charts" v-show="currBarTab == 2 && isOnlyTotal"></div>
            </div>
            <div class="right-tab">
                <ul>
                    <li v-for="item in barTab" :key="item.id" :class="[item.isActive && barDay.length == 0 ? 'tab-active' : '']" @click="selectTab(item.id ,'bar')">{{item.title}}</li>
                    <li :class="['date-box',barDay.length != 0 ?'tab-active':'']">
                        检索
                        <ekt-date-picker :pickDate="barDay" @handleChange="handleBarChangeTime"></ekt-date-picker>
                    </li>
                </ul>
                <div @click="showBarTotal" :class="isOnlyTotal ? 'is-active' : ''">仅总量</div>
            </div>
            <nav-switch
                :currSwitch="currBarSwitch"
                :stats="'bar'"
                @handleClick="showStats"
            />
        </el-card>

        <el-card class="box-card-bottom">
            <div class="time-tips">
              <span>以下为 {{monthTips}} 的数据</span>
              <quality-box v-if="getControl" :content="`${monthTips} 的数据`" :dateTips="monthTips" text="say医废数据总览按月分布"></quality-box>
            </div>
            <div class="data-bottom-box">
                <div ref="bar-total-half-year" class="total-charts" v-show="currMonthTab == 1 && !isOnlyMonthTotal"></div>
                <div ref="bar-total-all-year" class="total-charts" v-show="currMonthTab == 2 && !isOnlyMonthTotal"></div>
                
                <div ref="bar-total-half-year-only" class="total-charts" v-show="currMonthTab == 1 && isOnlyMonthTotal"></div>
                <div ref="bar-total-all-year-only" class="total-charts" v-show="currMonthTab == 2 && isOnlyMonthTotal"></div>
            </div>
            <div class="right-tab">
                <ul>
                    <li v-for="item in monthTab" :key="item.id" :class="[item.isActive && monthDay.length == 0 ? 'tab-active' : '']" @click="selectTab(item.id ,'month')">{{item.title}}</li>
                    <li :class="['date-box',monthDay.length != 0?'tab-active':'']">
                        检索
                        <ekt-date-picker :pickDate="monthDay" :rangeType="'monthrange'" :format="'yyyy-MM'" @handleChange="handleMonthChangeTime"></ekt-date-picker>
                    </li>
                </ul>
                <div @click="showMonthTotal" :class="isOnlyMonthTotal ? 'is-active' : ''">仅总量</div>
            </div>
            <nav-switch
                :currSwitch="currMonthSwitch"
                :stats="'month'"
                @handleClick="showStats"
            />
        </el-card>

        <el-dialog
            class="pie-pop"
            title=""
            :visible.sync="showPiePop"
            width="1000px">
            <div ref="pie-pop" style="width:960px;height:620px;"></div>
        </el-dialog>

        <!-- <el-dialog
            :visible.sync="isShowNoSign"
            width="80%"
            custom-class="no-sign-box dialog-radus"
            :show-close="false"
            :before-close="hideNoSignModal">
            <div slot="title" class="no-sign-header">
                <span class="el-dialog__title">未签收科室</span>
                <button class="export-btn" @click="exportNoSignExcel">导出</button>
            </div>
            <div class="no-sign-content">
                <ks-table :newTableData="noSignInfos" :tableCol="tableCol" @handleClick="handleSendMsg"/>
            </div> 
        </el-dialog> -->
    </div>
    <div v-else class="empty">
        暂无科室数据
    </div>
</div>
</template>
<script>
// 引入基本模板
const echarts = require('echarts/lib/echarts');
// 引入柱状图组件
require('echarts/lib/chart/bar');
require('echarts/lib/chart/pie');
require('echarts/lib/chart/line');
// 引入提示框、图例标记和title组件
require('echarts/lib/component/title');
require('echarts/lib/component/tooltip');
require('echarts/lib/component/legend');
require("echarts/lib/component/legendScroll");
require("echarts/lib/component/dataZoom");
import navSwitch from './components/navSwitch.vue';
import {makeWeekDate,makeMonthDate,makeTodayDate,getCurrWeekend,sheet2blob,openDownloadDialog,getUpperCase,sliceStrWrap} from '../../common/utils';
// import ksTable from './components/ksTable';
// import * as echarts from 'echarts'
import ektDatePicker from './components/ektDatePicker';
import { 
    postDetailsUrl, 
    getOverviewDataUrl, getOvMonthTotalUrl, getDateTotalUrl, 
    getMonthTotalUrl, getWeekTotalUrl, getDepartmentMyInfoUrl,
    wastecategoryUrl,
} from '../../common/ajax';
import { mixinControl } from '../../common/mixin';
import qualityBox from './components/qualityBox'
const baseUrl = process.env.NODE_ENV == 'development' ? '/api' : ''
export default {
    data(){
        return{
            overviewData:[
                { number: '0', title: '总收集' },  // id总数目
                { number: '0', title: '总数量' },    // 总num
                { number: '0 kg', title: '总重量' }, // 总weight
            ],
            monthRange:[],
            pieData: [],
            pieDay:[],
            barDay:[],
            monthDay:[],
            timeTips:{
                pie:'',
                bar:''
            },
            monthTips:'',
            barData:[],
            monthData:[],
            pieTab:[
                { id: 1, title: '今日', isActive: true },
                { id: 2, title: '本周', isActive: false },
                { id: 3, title: '当月', isActive: false }
            ],
            barTab:[
                { id: 1, title: '本周', isActive: true },
                { id: 2, title: '当月', isActive: false }
            ],
            monthTab:[
                { id: 1, title: '近半年', isActive: true },
                { id: 2, title: '今年', isActive: false }
            ],
            currPieTab: 1,
            currBarTab: 1,
            currMonthTab: 1,
            totalBarData: [],
            totalMonthData: [],
            isOnlyTotal: false,
            isOnlyMonthTotal: false,
            currPieSwitch: 1,
            currBarSwitch: 1,
            currMonthSwitch: 1,
            weekendLis: [],
            showPiePop:false,
            // 未签收
            isShowNoSign: false,
            noSignInfos: [], // 未签收的信息数
            noSignRooms: [], // 未签收的科室数
            tableCol: [],
            noSignData: [],
            exportTime: '',
            chartsDom: {
                onlyTotal: {
                    '1': 'bar-total-week-only', // 选择本周
                    '2': 'bar-total-month-only' // 选择当月
                },
                onlyMonthTotal: {
                    '1': 'bar-total-half-year-only',   // 选择近半年
                    '2': 'bar-total-all-year-only' // 选择今年
                },
                monthbar: {
                    '1': 'bar-total-half-year',    // 选择本周
                    '2': 'bar-total-all-year'  // 选择当月
                },
                pie: {
                    '1': 'pie-today',
                    '2': 'pie-week',
                    '3': 'pie-month',
                    '4': 'pie-days'
                },
                barTotal: {
                    '1': 'bar-total-week',  // 选择本周
                    '2': 'bar-total-month' // 选择当月
                },
            },
            pieText: {
              1: 'today',
              2: 'week',
              3: 'month'
            },
            barText: {
              1: 'week',
              2: 'month'
            },
            monthText: {
              1: 'half',
              2: 'all'
            },
            dataList: [],
            currVal: '',
            options: []
        }
    },
    components:{
        navSwitch,
        // ksTable,
        ektDatePicker,
        qualityBox
    },
    mounted(){
      this.getDataList();
    },
    mixins: [mixinControl],
    methods:{
      getDataList(){
        jQuery.ajax({
          url: wastecategoryUrl,
          success: res => {
            this.dataList = res.data;
            this.getDepartmentLis();
            this.weekendLis = getCurrWeekend();
          }
        })
      },
        handleSelect(val){
          this.currVal = val;
          this.initData();
        },
        getDepartmentLis(){
          jQuery.ajax({
            url: getDepartmentMyInfoUrl,
            success: function(res){
                if(!res.success || res.data.length == 0){
                    return
                }
              this.options = res.data.map(v => {
                return {
                  label: v.department,
                  value: v.department,
                }
              })
              this.currVal = this.options[0].value
              console.log(this.currVal);
              this.initData();
            }.bind(this)
          })
        },
        initData(){
          this.getOverviewData(this.pieText[this.currPieTab])
          this.getTypeCompareData(this.pieText[this.currPieTab])
          this.handleSetTimeTips(this.pieText[this.currPieTab],'pie')
          this.getTotalData(this.barText[this.currBarTab])
          this.handleSetTimeTips(this.barText[this.currBarTab],'bar')
          this.getMonthTotalData(this.monthText[this.currMonthTab])
          this.handleSetMonthTips(this.monthText[this.currMonthTab])
        },
        // handleSendMsg(val){
        //     let form = {
        //         place: val.unsign_data[0].place,
        //         total: val.unsign_data.reduce((prev, curr) => prev + parseInt(curr.total), 0),
        //         date: val.unsign_days
        //     }
        //     postAttentionTo(JSON.stringify(form)).then(res => {
        //         if(res.success) {
        //             this.msgTips('发送成功!', true, '#67c23a');
        //         }else{
        //             this.msgTips(res.msg, true);
        //         }
        //     })
        // },
        // exportNoSignExcel(){
        //     let header = `当前搜索结果为 ${this.exportTime} 时间段的数据，未签收科室 ${this.noSignRooms}，未签收 ${this.noSignData.length} 条信息`;
        //     let typeArr = [], typeTitleArr = [], excel = [], labelArr = ['楼栋', '楼层', '科室', '未签名日期']
        //     this.tableCol.forEach(v => {
        //         typeArr = typeArr.concat(v.label+'数量', v.label+'重量')
        //         typeTitleArr = typeTitleArr.concat('num'+v.prop.substr(4), 'value'+v.prop.substr(4))
        //     })
        //     typeArr.unshift(3, 0)
        //     Array.prototype.splice.apply(labelArr, typeArr)
        //     excel.push(labelArr)
        //     this.noSignInfos.forEach(v => {
        //         let arr = [], propArr = []
        //         arr.push(v.f, v.l, v.room_name, v.unsign_days.join('、').replace(/-/g,'/'))
        //         for(let i in typeTitleArr){
        //             let value = !v[typeTitleArr[i]] ? '0' : v[typeTitleArr[i]].toString()
        //             propArr.push(value)
        //         }
        //         propArr.unshift(3, 0)
        //         Array.prototype.splice.apply(arr, propArr)
        //         excel.push(arr)
        //     })
        //     excel.unshift([header])
        //     let sheet = this.$xlsx.utils.aoa_to_sheet(excel);
        //     openDownloadDialog(sheet2blob(sheet), `医废未签收科室 ${this.exportTime}.xlsx`);  
        // },
        hideNoSignModal(){
            this.isShowNoSign = false;
        },
        countNoSignData(item){ // 计算出未签收的科室数，所有未签收单数。（仅针对科室交接）
            this.noSignInfos = []
            let arr = item.filter(v => v.step1_uname == '')
            let roomArr = [];
            arr.forEach(v => {
                v.weight += 'kg'
                let dtime = v.ctime.split(' ')[0]
                let day = new Date(dtime).getDay()
                if(roomArr.indexOf(v.place) == -1) {    // 如果是新的科室，直接存整个数组
                    roomArr.push(v.place)
                    let obj = {
                        f: v.ld,
                        l: v.lc,
                        room_name: v.ks,
                        valueTotal: parseFloat(v.weight.substr(0,v.weight.length-2)).toFixed(2) == '' ? '0.00' : parseFloat(v.weight.substr(0,v.weight.length-2)).toFixed(2),
                        numTotal: parseInt(v.num) == '' ? 0 : parseInt(v.num),
                        sort_valueTotal: '0.00',
                        unsign_days: v.unsign_days.map(v => v.day),
                        unsign_total: v.unsign_days.map(v => v.total),
                        unsign_data: v.unsign_days
                    }
                    Object.assign(obj, {
                        id: v.idwc,
                        date: [
                            {
                                date: dtime.split('-')[2],
                                day: day.toString(),
                                disabled: "",
                                isActive: "",
                                month: dtime.split('-')[1],
                                status: "start-date",
                                year: dtime.split('-')[0]
                            }
                        ],
                        canShowDate: false,
                        [`value${v.idwc}`]: parseFloat(v.weight.substr(0,v.weight.length-2)).toFixed(2) == '' ? '0.00' : parseFloat(v.weight.substr(0,v.weight.length-2)).toFixed(2),
                        [`num${v.idwc}`]: parseInt(v.num) == '' ? 0 : parseInt(v.num),
                        [`sort_value${v.idwc}`]: parseFloat(v.weight.substr(0,v.weight.length-2)).toFixed(2) == '' ? '0.00' : parseFloat(v.weight.substr(0,v.weight.length-2)).toFixed(2),
                    })
                    this.noSignInfos.push(obj)
                }else{  // 如果已有这个科室，则找到对应科室，再找是否有对应的类型idwc，如果没有，则直接添加，有，则找到后再累加num和weight
                    this.noSignInfos.forEach(v2 => {
                        if(v2.f == v.ld && v2.l == v.lc && v2.room_name == v.ks){
                            let weight = parseFloat(v.weight.substr(0,v.weight.length-2)),
                                num = parseInt(v.num);
                            v2[`value${v.idwc}`] = !v2[`value${v.idwc}`] ? weight.toFixed(2) : parseFloat(parseFloat(v2[`value${v.idwc}`]) + weight).toFixed(2)
                            v2[`num${v.idwc}`] = !v2[`num${v.idwc}`] ? num : parseInt(v2[`num${v.idwc}`]) + num
                            v2.valueTotal = parseFloat(parseFloat(v2.valueTotal) + weight).toFixed(2)
                            v2.numTotal = v2.numTotal + num
                            v2[`sort_value${v.idwc}`] = parseFloat(v2[`value${v.idwc}`])
                            v2.sort_valueTotal = parseFloat(v2.valueTotal)
                        }
                    })
                }
            })
            this.noSignRooms = roomArr.length;
        },
        postAllData(){
            let st = '', et = '';
            if(this.pieDay.length != 0){
                st = this.pieDay[0]
                et = this.pieDay[1]
            }else if(this.currPieTab == 1){
                st = et = makeTodayDate()
            }else if(this.currPieTab == 2){
                st = makeWeekDate()[0]
                et = makeWeekDate()[6]
            }else if(this.currPieTab == 3){
                st = makeMonthDate().s
                et = makeMonthDate().e
            }
            let form = {
                st: st,
                et: et,
                filter_ks: [],
                cs: this.dataList.filter(v => v.hang != 1).map(v2 => v2.id),
                shm: '',
                ehm: ''
            }
            jQuery.ajax({
              url: postDetailsUrl,
              type: 'POST',
              data: JSON.stringify(form),
              success: function(res) {
                this.noSignData = [];
                if(res.data.length > 0) {
                    this.countNoSignData(res.data);
                    this.noSignData = res.data.filter(v => v.step1_uname == '');
                }
                this.getTableCol();
              }.bind(this)
            })
        },
        showModal(){
            this.isShowNoSign = true;
        },
        getTableCol(){
            let typeName = [], col = []
            this.noSignData.forEach(v => {  // 获取所有出现过的类型名
                if(typeName.indexOf(v.namewc) == -1) {
                    typeName.push(v.namewc)
                    col.push({
                        prop: `type${v.idwc}`,
                        label: v.namewc,
                        colour: v.colour
                    })
                }
            })
            col.push({
                prop: 'typeTotal',
                label: '未签收医废合计'
            })
            this.tableCol = col;
        },
        showStats(tag, num){
            if(tag == 'pie')  {
                this.currPieSwitch = num
                this.paintPie(this.currPieTab)
            }
            if(tag == 'bar')  {
                this.currBarSwitch = num
                if(this.isOnlyTotal) {
                    this.getOnlyTotalData()
                    return;
                }
                this.paintBar(this.currBarTab)
            }
            if(tag == 'month') {
                this.currMonthSwitch = num
                if(this.isOnlyMonthTotal){
                    this.getOnlyMonthTotalData()
                    return;
                }
                this.paintMonthBar(this.currMonthTab)
            }
        },
        getOverviewData(txt){      // 获取总览数字
            this.isOnlyTotal = false;
            let json = {st:'', et:''}
            if(txt == 'week'){
                json.st = makeWeekDate()[0]
                json.et = makeWeekDate()[6]
            }else if(txt == 'month'){
                json.st = makeMonthDate().s
                json.et = makeMonthDate().e
            }else if(txt == 'today'){
                json.st = makeTodayDate()
            }else {
                json.st = this.pieDay[0]
                json.et = this.pieDay[1]
            }
            if(this.overviewData.length == 4) this.overviewData.pop();
            jQuery.ajax({
              url: getOverviewDataUrl,
              data: {
                st: json.st,
                et: json.et,
                place: this.currVal
              },
              success: function(res) {
                this.overviewData[0].number = res.data.count;
                this.overviewData[1].number = res.data.num;
                this.overviewData[2].number = res.data.weight_all;
                if(res.data.step0_hours != 0){
                    this.overviewData.push({
                        number: `${res.data.step0_hours_count} / ${res.data.step0_hours_weight}kg`,
                        title: `${res.data.step0_hours}小时未交接`
                    })
                    switch(res.data.step0_hours){
                        case 24: this.exportTime = makeTodayDate(); break;
                        case 48: this.exportTime = makeWeekDate()[0] + '至' + makeWeekDate()[1]; break;
                        case 72: this.exportTime = makeWeekDate()[0] + '至' + makeWeekDate()[2]; break;
                    }
                    this.postAllData()
                }
              }.bind(this)
            })
        },
        getTypeCompareData(text){      // 获取类型对比数据
            let url = text ? `/w/wastecategory/ov/pie/${text}?place=${this.currVal}` : `/w/wastecategory/ov/pie/period?st=${this.pieDay[0]}&et=${this.pieDay[1]}&place=${this.currVal}`
            if(!text) this.currPieTab = 1
            // let param = text || this.pieDay
            jQuery.ajax({
              url: baseUrl+url,
              type: 'GET',
              // data: param,
              success: function(res) {
                this.pieData = res.data;
                let num = 0;
                switch(text){
                    case 'week': num = 2; break;
                    case 'month': num = 3; break;
                    default: num = 1; break;
                }
                this.paintPie(num)
              }.bind(this)
            })
        },
        getTotalData(text){      // 获取总量对比数据
            let url = this.barDay.length != 0 ? getDateTotalUrl : text == 'month' ? getMonthTotalUrl : getWeekTotalUrl
            let params = this.barDay.length != 0 ? {
                st: this.barDay[0],
                et: this.barDay[1]
            } : {}
            Object.assign(params, {
              place: this.currVal
            })

            jQuery.ajax({
              url: url,
              data: params,
              success: function(res) {
                this.barData = res.data
                let num = text == 'week' ? 1 : 2
                this.paintBar(num)
              }.bind(this)
            })
        },
        getOnlyTotalData(){
            let newArr = [];
            if(this.currBarTab == 1){
                this.barData.forEach(v => {
                    let num = 0.0;
                    v.val.forEach(v2 => {
                        num += parseFloat(this.currBarSwitch == 1 ? v2.total : v2.num)
                    })
                    newArr.push(Object.assign({}, v, {
                        value: this.currBarSwitch == 1 ? num.toFixed(2) : num
                    }))
                })
            }else{
                this.barData.forEach(v => {
                    let num = 0.0;
                    v.val.forEach(v2 => {
                        num += parseFloat(this.currBarSwitch == 1 ? v2.total : v2.num)
                    })
                    newArr.push(Object.assign({}, v, {
                        value: this.currBarSwitch == 1 ? num.toFixed(2) : num
                    }))
                })
            }
            this.totalBarData = newArr.map(v => v)
            this.paintOnlyTotal(this.currBarTab)
        },
        showBarTotal(){
            if(this.isOnlyTotal) {
                this.isOnlyTotal = false;
                this.paintBar(this.currBarTab)
                return;
            }
            this.isOnlyTotal = true;
            this.getOnlyTotalData()
        },
        getMonthTotalData(text){      // 获取总量对比数据
            let smonth = '', emonth = '';
            if(this.monthDay.length == 0){
                let start = '', end = '';
                if(text == 'half'){
                    start = new Date();
                    end = new Date();
                    start.setMonth(start.getMonth() - 5)
                }
                if(text == 'all'){
                    start = new Date(new Date().getFullYear(), 0);
                    end = new Date();
                }
                smonth = `${start.getFullYear()}-${`00${start.getMonth() + 1}`.substr(-2)}`
                emonth = `${end.getFullYear()}-${`00${end.getMonth() + 1}`.substr(-2)}`
            }
            jQuery.ajax({
              url: getOvMonthTotalUrl,
              data: {
                smonth: smonth == '' ? this.monthDay[0] : smonth,
                emonth: emonth == '' ? this.monthDay[1] : emonth,
                place: this.currVal
              },
              success: res => {
                this.monthData = res.data
                let num = text == 'half' ? 1 : 2
                this.paintMonthBar(num)
              }
            })
        },
        getOnlyMonthTotalData(){
            let newArr = [];
            if(this.currMonthTab == 1){
                this.monthData.forEach(v => {
                    let num = 0.0;
                    v.val.forEach(v2 => {
                        num += parseFloat(this.currMonthSwitch == 1 ? v2.total : v2.num)
                    })
                    newArr.push(Object.assign({}, v, {
                        value: this.currMonthSwitch == 1 ? num.toFixed(2) : num
                    }))
                })
            }else{
                this.monthData.forEach(v => {
                    let num = 0.0;
                    v.val.forEach(v2 => {
                        num += parseFloat(this.currMonthSwitch == 1 ? v2.total : v2.num)
                    })
                    newArr.push(Object.assign({}, v, {
                        value: this.currMonthSwitch == 1 ? num.toFixed(2) : num
                    }))
                })
            }
            this.totalMonthData = newArr.map(v => v)
            this.paintOnlyMonthTotal(this.currMonthTab)
        },
        showMonthTotal(){
            if(this.isOnlyMonthTotal) {
                this.isOnlyMonthTotal = false;
                this.paintMonthBar(this.currMonthTab)
                return;
            }
            this.isOnlyMonthTotal = true;
            this.getOnlyMonthTotalData()
        },
        selectTab(id, tabType){
            if(tabType != 'month'){
                this.isOnlyTotal = false;
            }else{
                this.isOnlyMonthTotal = false;
            }
            if(tabType == 'pie'){
                if(id != this.currPieTab || this.pieDay) {
                    let text = ''
                    switch(id){
                        case 2: text = 'week'; break;
                        case 3: text = 'month'; break;
                        default: text = 'today'; break;
                    }
                    this.pieDay = []
                    this.getTypeCompareData(text)
                    this.getOverviewData(text)
                    this.handleSetTimeTips(text,'pie')
                }
                this.currPieTab = id
                this.pieTab.forEach(v => {
                    v.isActive = v.id == id ? true : false
                })
            }else if(tabType == 'bar'){
                this.barDay = []
                if(id != this.currBarTab) this.paintBar(id)
                this.currBarTab = id
                this.barTab.forEach(v => {
                    v.isActive = v.id == id ? true : false
                })
                this.currBarTab == 1 ? (this.getTotalData('week'), this.handleSetTimeTips('week','bar')) : (this.getTotalData('month'), this.handleSetTimeTips('month','bar'))
            }else if(tabType == 'month'){
                this.monthDay = []
                if(id != this.currMonthTab) this.paintMonthBar(id)
                this.currMonthTab = id
                this.monthTab.forEach(v => {
                    v.isActive = v.id == id ? true : false
                })
                this.currMonthTab == 1 ? (this.getMonthTotalData('half'), this.handleSetMonthTips('half')) : (this.getMonthTotalData('all'), this.handleSetMonthTips('all'))
            }
        },
        handlePieChangeTime(e){
            this.pieDay = e;
            this.getOverviewData()
            this.getTypeCompareData()
            this.handleSetTimeTips('','pie')
        },
        handleBarChangeTime(e){
            this.barDay = e;
            this.isOnlyTotal = false;
            this.paintBar(2)
            this.currBarTab = 2
            this.getTotalData('month')
            this.handleSetTimeTips('','bar')
        },
        handleMonthChangeTime(e){
            this.monthDay = e;
            this.isOnlyMonthTotal = false;
            this.paintMonthBar(2)
            this.currMonthTab = 2
            this.getMonthTotalData()
            this.handleSetMonthTips('')
        },
        handleSetMonthTips(txt){
            let json = {st:'', et:''}
            if(txt == 'half'){
                const start = new Date();
                const end = new Date();
                start.setMonth(start.getMonth() - 5);
                json.st = `${start.getFullYear()}-${`00${start.getMonth() + 1}`.substr(-2)}`
                json.et = `${end.getFullYear()}-${`00${end.getMonth() + 1}`.substr(-2)}`
            }else if(txt == 'all'){
                const start = new Date(new Date().getFullYear(), 0);
                const end = new Date();
                json.st = `${start.getFullYear()}-${`00${start.getMonth() + 1}`.substr(-2)}`
                json.et = `${end.getFullYear()}-${`00${end.getMonth() + 1}`.substr(-2)}`
            }else{
                json.st = this.monthDay[0]
                json.et = this.monthDay[1]
            }
            this.monthTips = json.st
            if(json.st != json.et && json.et){
                this.monthTips += ' 至 '+json.et
            }
        },
        handleSetTimeTips(txt,opt){
            let json = {st:'', et:''}
            if(txt == 'week'){
                json.st = makeWeekDate()[0]
                json.et = makeWeekDate()[6]
            }else if(txt == 'month'){
                json.st = makeMonthDate().s
                json.et = makeMonthDate().e
            }else if(txt == 'today'){
                json.st = makeTodayDate()
            }else {
                opt == 'pie' ?
                    (json.st = this.pieDay[0],json.et = this.pieDay[1]):
                    (json.st = this.barDay[0],json.et = this.barDay[1])
            }
            this.timeTips[opt] = json.st
            if(json.st != json.et && json.et){
                this.timeTips[opt] += ' 至 '+json.et
            }
        },
        getBaseBarOption(){
            return {
                tooltip: {      // 经过每项时的提示标记
                    trigger: 'axis',
                    axisPointer : {
                        type : 'shadow'
                    }
                },
                grid:{      // 调节表格网格位置
                    show: true,
                    top: '30',
                    bottom: '20%',
                    right: '0',
                    containLabel: true
                },
                yAxis: {
                    type : 'value'
                },
                dataZoom:[      // 底部缩放bar条
                    {
                        show: true,
                        start: 1,
                        end: 100
                    },
                    {
                        type: 'inside',
                        start: 1,
                        end: 100
                    }
                ],
            }
        },
        getBarOption(text, opt){
            let name = text.charAt(0).toUpperCase() + text.slice(1)
            return Object.assign({}, this.getBaseBarOption(), {
                color: this.dataList.filter(v => v.hang != 1).map(v => v.colour),
                legend: {       // 图例组件，可以点击来实现显示或者隐藏
                    type: 'scroll',
                    orient: 'vertical',
                    left: 'left',
                    top:'10',
                    height: 300,
                    textStyle:{
                        lineHeight:20,
                    },
                    data: this.dataList.filter(v => v.hang != 1),
                    formatter: function(params){
                      return sliceStrWrap(params, 5)
                    }
                },
                xAxis: [opt],       // x轴显示日期，本周周一到周日or当月
                series: this.dataList.filter(v => v.hang != 1).map(v => {
                    let arr = []
                    arr = this[`${text}Data`].map(v2 => {
                        let num = 0;
                        if(v2.val.length == 0) {
                            num = 0;
                        }else{
                            let tmp = v2.val.findIndex(v3 => v3.name == v.name)
                            if(tmp != -1){
                                num = this[`curr${name}Switch`] == 1 ? v2.val[tmp].total : v2.val[tmp].num
                            }else{
                                num = this[`curr${name}Switch`] == 1 ? tmp.total : tmp.num
                            }
                            if(this[`curr${name}Switch`] == 1) num = parseFloat(num).toFixed(2)
                        }

                        if(num == 0){   // 当数值为0时，不显示
                            return {
                                value: 0,
                                label: {
                                    show: false
                                }
                            }
                        }
                        if(Number.isNaN(parseInt(num))){    // 避免某天内其中一个类型无数据时，不显示0
                            return {
                                value: 0.00,
                                label: {
                                    show: true
                                }
                            }
                        }
                        return num;
                    })
                    return{
                        name: v.name,
                        type: 'bar',
                        label: {        // 柱状图上每项的数值显示
                            show: true,
                            position:'top',
                            formatter: this[`curr${name}Switch`] == 1 ? "{c}kg" : "{c}"
                        },
                        data: arr
                    }
                })
            })
        },
        getOnlyBarOption(text, opt){
            let name = text.charAt(0).toUpperCase() + text.slice(1)
            return Object.assign({}, this.getBaseBarOption(), {
                color: '#fb587a',
                xAxis: [opt],
                series: [{
                    data: this[`total${name}Data`].map(v => {
                        if(v.value == 0){
                            return {
                                value: 0,
                                label: {
                                    show: false
                                }
                            }
                        }
                        return v
                    }),
                    type: 'bar',
                    label: {        // 柱状图上每项的数值显示
                        show: true,
                        position:'top',
                        formatter: this[`curr${name}Switch`] == 1 ? "{c}kg" : "{c}"
                    }
                }]
            })
        },
        getNormalAxis(id){
            return {
                type: 'category',
                data: this.barData.map(v => id == 1 ? `${v.key.substr(8)}日` : v.key.substr(8)),
                axisLabel:{
                    fontSize: 16,    // 字体大小设置
                    textStyle: {
                        color: (value, index) => {
                            if(this.currBarTab == 1){
                                return index > 4 ? 'red' : '#333'
                            }else{
                                return this.weekendLis.indexOf(parseInt(value)) != -1 ? 'red' : '#333'
                            }
                        }
                    }
                }
            }
        },
        getMonthAxis(){
            return {
                type: 'category',
                data: this.monthData.map(v => `${v.key.substr(5)}月`),
                axisLabel:{
                    fontSize: 16,    // 字体大小设置
                }
            }
        },
        paintOnlyTotal(id){
            echarts.init(this.$refs[this.chartsDom.onlyTotal[id]]).setOption(this.getOnlyBarOption('bar', this.getNormalAxis(id)))
        },
        paintOnlyMonthTotal(id){
            echarts.init(this.$refs[this.chartsDom.onlyMonthTotal[id]]).setOption(this.getOnlyBarOption('month', this.getMonthAxis()))
        },
        paintMonthBar(id){
            echarts.init(this.$refs[this.chartsDom.monthbar[id]]).setOption(this.getBarOption('month', this.getMonthAxis()))
        },
        paintBar(id){
            echarts.init(this.$refs[this.chartsDom.barTotal[id]]).setOption(this.getBarOption('bar', this.getNormalAxis(id)))
        },
        getPieOption(opt, fontSize){
            return {
                tooltip: {
                    trigger: 'item',
                    formatter: "{b} : {c} ({d}%)"
                },
                legend: {       // 图例组件，可以点击来实现显示或者隐藏
                    orient: 'vertical',
                    left: 'left',
                    bottom:'10',
                    data: this.dataList.filter(v => v.hang != 1)
                },
                series: [Object.assign({}, {
                    name: '',
                    type: 'pie',
                    label: {        // 柱状图上每项的数值显示
                        show: true,
                        position:'outside', // 标签位置
                        formatter: this.currPieSwitch == 1 ? "{b}\n{c}kg" : "{b}\n{c}"  // 标签内容,选择显示重量时,带kg单位. {b}数据名{c}数值名
                    },
                    data: this.pieData.filter(v => v.hang != 1).map(v => {  // 禁用的类型不显示
                        return{
                            value: this.currPieSwitch == 1 ? parseFloat(v.total).toFixed(2) : v.num,
                            name: v.name,
                            itemStyle: {
                                color: v.colour
                            },
                            label: {
                                fontSize: fontSize
                            }
                        }
                    })
                }, opt)]
            }
        },
        paintPie(id){
            echarts.init(this.$refs[this.chartsDom.pie[id]]).setOption(this.getPieOption({
                radius : '50%',
                center: ['58%', '50%'],     // 设置拼图的位置
            }, 13))
        },
        handleShowBigPaintPie(){
            if(this.pieData.length == 0) return
            this.showPiePop = true
            setTimeout(_=>{
                echarts.init(this.$refs['pie-pop']).setOption(this.getPieOption({
                    radius : '50%',
                    center: ['66%', '50%'],     // 设置拼图的位置
                }, 15))
            },400)
        }
    }
}
</script>
<style lang="less">
@import '../../assets/less/statistics-data.less';
@import '../../assets/less/data-overview.less';

.statistics-data-box.graph-modal-box{
    min-height: auto;
    height: auto;
    padding: 15px 0;
    .filter-part{
      margin-bottom: 20px;
    }
}
.data-overview-box .hour-set-modal .group-list button:nth-of-type(1){
    border-color: #ccc;
}

.el-input__inner{
    padding: 0 5px;
}

.pie-charts{
    width: 420px;
    height: 230px;
}

.total-charts{
    width:1000px;
    height:425px;
}

.pie-pop .el-dialog__header {
    display: none;
}
</style>
